<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class CustomerAppletsCouponUsers extends Model
{
    protected $table      = "customerapplets_coupon_users";
    protected $primaryKey = "id";

    /**
     * 创建用户领取卡券记录数据
     * @param $userCoupon
     * @return array
     */
    public function createCouponUser($userCoupon){

        $userCouponResult = $this->where(['user_id' => $userCoupon['user_id'],'store_id' => $userCoupon['store_id'],'stock_id' => $userCoupon['stock_id']])->first();
        if(!empty($userCouponResult)){
            if($userCouponResult->is_use_coupon == 2){
                return ["status" => 202,'message' => "该卡券已领取"];
            }
        }

        DB::beginTransaction();
        try{
            $date = date("Y-m-d H:i:s",time());
            $coupon['user_id']         = $userCoupon['user_id'];
            $coupon['store_id']        = $userCoupon['store_id'];
            $coupon['stock_id']        = $userCoupon['stock_id'];
            $coupon['coupon_code']     = $userCoupon['coupon_code'];
            $coupon['is_use_coupon']   = 2;
            $coupon['created_at']      = $date;
            $coupon['updated_at']      = $date;
            $this->insert($coupon);
            DB::commit();
            return ["status" => 200,'message' => "创建成功"];
        }catch (\Exception $e){
            DB::rollBack();
            return ["status" => 202,'message' => $e->getMessage()];
        }
    }


    /**
     * 卡券进行核销
     * @param $receive_coupon_id 领取卡券记录主键id
     * @param $wechatpay_use_time 微信接口返回的卡券核销时间
     * @param $openid             微信接口返回的卡券核销人
     * @return array
     */
    public function userUseCoupon($receive_coupon_id,$wechatpay_use_time,$openid){
        $couponResult = $this->where(['id' => $receive_coupon_id])->first();
        if(!empty($couponResult)){
            if($couponResult->is_use_coupon == 1){
                return ['status' => 202,"message" => "该卡券记录已核销"];
            }

            DB::beginTransaction();
            try{
                $updateCoupon['is_use_coupon']      = 1;
                $updateCoupon['wechatpay_use_time'] = $wechatpay_use_time;
                $updateCoupon['openid']             = $openid;
                $updateCoupon['updated_at']         = date("Y-m-d H:i:s",time());
                $this->where(['id' => $receive_coupon_id])->update($updateCoupon);
                DB::commit();
                return ["status" => 200,'message' => "核销成功"];
            }catch (\Exception $e){
                DB::rollBack();
                return ["status" => 202,'message' => $e->getMessage()];
            }
        }else{
            return ['status' => 202,"message" => "领取记录信息不存在"];
        }
    }

    /**
     * 获取用户的卡券
     * @param $user_id
     * @param $store_id
     * @param $status
     *        1:领取已使用
     *        2:领取未使用
     *        3:过期状态
     * @param $money
     * @return mixed
     */
    public function getUserCoupon($user_id,$store_id,$status,$money = ""){
        $result = $this->select("customerapplets_coupon_users.id","customerapplets_coupons.id as coupon_id","customerapplets_coupon_users.stock_id","customerapplets_coupon_users.coupon_code",
                "customerapplets_coupon_users.is_use_coupon","customerapplets_coupon_users.wechatpay_use_time","customerapplets_coupon_users.openid",
                "customerapplets_coupons.coupon_stock_name","customerapplets_coupons.available_begin_time","customerapplets_coupons.available_end_time",
                "customerapplets_coupons.discount_amount","customerapplets_coupons.transaction_minimum")
                ->leftJoin("customerapplets_coupons","customerapplets_coupons.stock_id","=","customerapplets_coupon_users.stock_id")
                ->where(["customerapplets_coupon_users.user_id" => $user_id,"customerapplets_coupon_users.store_id" => $store_id]);
        $date = date("Y-m-d H:i:s",time());
        if($status == 1){
            $result = $result->where(["customerapplets_coupon_users.is_use_coupon" => 1])->where("customerapplets_coupons.available_end_time",">",$date);
        }else if($status == 2){
            $result = $result->where(["customerapplets_coupon_users.is_use_coupon" => 2])->where("customerapplets_coupons.available_end_time",">",$date);
        }else{
//            $result = $result->where("customerapplets_coupons.available_end_time","<=",$date);
            $result = $result;
        }
        //消费门槛的过滤
        if(!empty($money)){
            $result = $result->where("customerapplets_coupons.transaction_minimum",'<=',$money);
        }
        $result = $result->get();
        return $result;
    }

    /**
     * 微信代金券查询条件
     */
    private function getCashCouponMap($input)
    {
        $map = [];

        // 门店id
        if (!empty($input['store_id'])) {
            $map['a.store_id'] = $input['store_id'];
        }
        // 批次号
        if (!empty($input['stock_id'])) {
            $map['a.stock_id'] = $input['stock_id'];
        }
        // 会员名
        if (!empty($input['user_name'])) {
            $map['a.user_name'] = $input['user_name'];
        }
        // 会员id
        if (!empty($input['openid'])) {
            $map['a.openid'] = $input['openid'];
        }
        // 使用状态
        if (!empty($input['status'])) {
            $date_now = date('Y-m-d H:i:s', time());
            switch ($input['status']) {
                case 1: // 可用
                    $map[] = ['b.available_begin_time', '<=', $date_now];
                    $map[] = ['b.available_end_time', '>=', $date_now];
                    $map[] = ['a.is_use_coupon', '=', 2];
                    break;
                case 2: // 已核销
                    $map[] = ['a.is_use_coupon', '=', 1];
                    break;
                case 3: // 已过期
                    $map[] = ['b.available_end_time', '<=', $date_now];
                    break;
                default :
                    break;
            }
        }

        return $map;
    }

    /**
     * 获取微信代金券领用列表
     */
    public function getCashCouponUseList($input)
    {
        $map = $this->getCashCouponMap($input);

    }

    public function getUserGetCashCouponCount($input)
    {
        $map = $this->getCashCouponMap($input);

        return $this->from('customerapplets_coupon_users as a')->where($map)
            ->leftjoin('customerapplets_coupons as b', function ($join) {
                $join->on('a.stock_id', '=','b.stock_id')
                    ->on('a.store_id', '=','b.store_id');
            })
            ->count();
    }

    /**
     * 获取微信代金券领用、核销分页列表（用户）
     */
    public function getUserGetCashCouponPageList($input, $start, $limit)
    {
        $map = $this->getCashCouponMap($input);

        return $this->from('customerapplets_coupon_users as a')->where($map)
            ->selectRaw("
                sum(IF(a.is_use_coupon = '1', 1, 0)) AS user_used_num, count(a.id) AS user_sent_num, 
                sum(IF(a.is_use_coupon = '2', 1, 0)) AS user_can_used_num, a.user_name, a.openid, 
                b.available_begin_time, b.available_end_time                
            ")
            ->leftjoin('customerapplets_coupons as b', function ($join) {
                $join->on('a.stock_id', '=','b.stock_id')
                    ->on('a.store_id', '=','b.store_id');
            })
            ->groupBy('a.openid')
            ->skip($start)->limit($limit)
            ->get();
    }

    /**
     * 核销代金券明细条件
     * @param $input
     * @return array
     */
    private function getCashCouponUsedMap($input)
    {
        $map = [];
        $map['a.coupon_type']   = 2;
        $map['a.is_use_coupon'] = 1;

        // // 门店id
        // if (!empty($input['store_id'])) {
        //     $map['a.store_id'] = $input['store_id'];
        // }
        // 商户号 wx_sub_merchant_id
        if (!empty($input['wx_sub_merchant_id'])) {
            $map['a.consume_mchid'] = $input['wx_sub_merchant_id'];
        }
        // 代金券名称
        if (!empty($input['coupon_name'])) {
            $map['a.coupon_name'] = $input['coupon_name'];
        }
        // 代金券名称
        if (!empty($input['coupon_name'])) {
            $map['a.coupon_name'] = $input['coupon_name'];
        }
        // 代金券名称
        if (!empty($input['coupon_name'])) {
            $map['a.coupon_name'] = $input['coupon_name'];
        }

        return $map;
    }

    /**
     * 代金券核销数量
     * @param $input
     * @return mixed
     */
    public function getCashCouponUsedCount($input)
    {
        $map = $this->getCashCouponUsedMap($input);

        return $this->from('customerapplets_coupon_users as a')
            ->select([
                'a.coupon_name', 'a.stock_id', 'a.wechatpay_use_time', 'a.id', 'a.coupon_amount',
                'a.transaction_minimum', 'a.status', 'a.create_time'
            ])
            ->where($map)->count();
    }

    /**
     * 代金券核销明细列表
     * @param $input
     * @param $start
     * @param $limit
     * @return mixed
     */
    public function getCashCouponUsedPageList($input, $start, $limit)
    {
        $map = $this->getCashCouponUsedMap($input);

        // DB::enableQueryLog();  //开启日志
        // var_dump(DB::getQueryLog());die; //打印日志
        return $this->from('customerapplets_coupon_users as a')->where($map)
            ->select([
                'a.coupon_name', 'a.stock_id', 'a.wechatpay_use_time', 'a.id', 'a.coupon_amount',
                'a.transaction_minimum', 'a.status', 'a.create_time'
            ])
            ->skip($start)->limit($limit)
            ->get();
    }

}